/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.devel.designpatterns.visitor;

import com.devel.designpatterns.composite.Composite;
import com.devel.designpatterns.composite.Leaf;
import java.io.PrintStream;
import java.util.ArrayList;

/**
 *
 * @author wm.devel
 */
public class JSONEncodeVisitor extends Visitor {
    
    private PrintStream out;
    private int level = 0;
    private ArrayList<Integer> comma = new ArrayList<>();

    public JSONEncodeVisitor(PrintStream out) {
        this.out = out;
        comma.add(0);
    }

    public JSONEncodeVisitor() {
        this(System.out);
    }  
    
    protected void printIndent() {
        for (int i = 0; i < level; i++)
            System.out.print("  ");
    }
    
    protected void printComma(){
        int count = comma.get(comma.size() - 1);
        comma.remove(comma.size() - 1);
        comma.add(--count);
        if (count > 0)
            out.println(",");
        else
            out.println();
    }
    
    @Override
    public void visitCompositeStart(Composite composite) {
        if (level == 0) {
            printIndent();
            out.println("{");
        }
        
        level++;
        printIndent();
        out.println("\"Composite\": {");
        
        comma.add(composite.size());

        level++;
        printIndent();
        out.println("\"size\": " + composite.size() + ",");
        printIndent();
        out.println("\"children\": [ {");
    }

    @Override
    public void visitCompositeEnd(Composite composite) {
        printIndent();
        out.println("} ]");
        level--;
        
        printIndent();
        out.print("}");

        comma.remove(comma.size() - 1);
        level--;
        printComma();
        
        if (level == 0) {
            printIndent();
            out.println("}");
        }
    }

    @Override
    public void visitLeaf(Leaf leaf) {
        level++;
        printIndent();
        out.println("\"Leaf\": {");

        level++;
        printIndent();
        out.println("\"text\": \"" + leaf.getText() + "\"");
        level--;
        
        printIndent();
        out.print("}");
        printComma();
        level--;
        
        //if (comma.get(level) )
    }
    
}
